import React, { useEffect, useState } from 'react';
import { Select, Space } from 'antd';

interface IProps {
  // eslint-disable-next-line react/require-default-props
  id?: string;
  // eslint-disable-next-line react/require-default-props
  onChange?: (value: any) => void;
  // eslint-disable-next-line react/require-default-props
  value?: any;
  // eslint-disable-next-line react/require-default-props
  required?: boolean;
}

const App: React.FC<IProps> = props => {
  const { id, value = {}, onChange, required } = props;
  const [val_1, setVal_1] = useState();
  const [val_2, setVal_2] = useState();
  const [val_3, setVal_3] = useState();
  const [options_1, setOptions_1] = useState([]);
  const [options_2, setOptions_2] = useState([]);
  const [options_3, setOptions_3] = useState([]);

  const triggerChange = () => {
    const values = { ...value, key1: val_1, key2: val_2, key3: val_3 };
    onChange?.(values);
  };

  const handlerChange = async (index, val) => {
    if (index === 0) {
      setVal_1(val);
      try {
        const res = await Promise.resolve(['b1', 'b2', 'b3']);
        setOptions_2(res);
      } catch (error) {
        console.log(error);
      }
    }
    if (index === 1) {
      setVal_2(val);
      try {
        const res = await Promise.resolve(['c1', 'c2', 'c3']);
        setOptions_3(res);
      } catch (error) {
        console.log(error);
      }
    }
    if (index === 2) {
      setVal_3(val);
    }
  };
  useEffect(() => {
    if (value?.key1) {
      handlerChange(0, value.key1);
    }
    if (value?.key2) {
      handlerChange(1, value.key2);
    }
  }, [value]);

  useEffect(() => {
    if (!val_1) {
      setVal_2(undefined);
      setOptions_2([]);
    }

    if (!val_2) {
      setVal_3(undefined);
      setOptions_3([]);
    }
    triggerChange();
  }, [val_1, val_2, val_3]);

  useEffect(() => {
    _getOptions();
  }, []);

  async function _getOptions() {
    try {
      const res = await Promise.resolve(['a1', 'a2', 'a3']);
      setOptions_1(res);
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <Space wrap id={id}>
      <Select
        value={value?.key1 || val_1}
        style={{ width: 150 }}
        onChange={val => handlerChange(0, val)}
        options={options_1.map(province => ({ label: province, value: province }))}
        placeholder="省(自治区、直辖市)"
        allowClear
      />
      <Select
        value={value?.key2 || val_2}
        style={{ width: 150 }}
        onChange={val => handlerChange(1, val)}
        options={options_2.map(province => ({ label: province, value: province }))}
        placeholder="地(区、市、州、盟)"
        allowClear
      />
      <Select
        value={value?.key3 || val_3}
        style={{ width: 150 }}
        onChange={val => handlerChange(2, val)}
        options={options_3.map(province => ({ label: province, value: province }))}
        placeholder="县(市、区、旗)"
        allowClear
      />
    </Space>
  );
};

export default App;
